package com.splatter;


import java.io.IOException;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;

import com.chat.chatter.ejb.Emf;
import com.chat.chatter.ejb.Splat;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;


public class PlayClip extends HttpServlet {
	
	private static final long serialVersionUID = 1881413440711441953L;
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {  
		String requestUserId = request.getParameter("userId");  
		String requestKey = request.getParameter("key");        
		byte[] result = getClip( requestUserId, requestKey );         
		request.setAttribute("href", result);  
		
		//decode to byteArray
		byte[] clip = decode( result );
		//UTF-8?
		if (clip.length > 0){
			//audio/wav will work also
			response.setContentType( "audio/x-wav" /*audio/x-wav*/ );
			response.setHeader( "Content-Disposition", "attachment;filename=" + requestKey + ".wav" );
			response.setIntHeader( "Content-length", clip.length );
			response.setStatus(HttpServletResponse.SC_OK);
			ServletOutputStream out = response.getOutputStream();
			out.write(clip);
			out.flush();
			out.close();
			
			/*this works fine audio format is problem on other way
			file sits in war/WEB-INF
			File file = new File("whatcanthedo.wav");
	        FileInputStream inputStream = new FileInputStream(file);
	        byte[] bs = new byte[(int) file.length()]; 
	        inputStream.read(bs); 
	        inputStream.close(); 
	        response.setContentType("audio/x-wav");
	        response.setContentLength(bs.length);
	        ServletOutputStream stream = response.getOutputStream();         
	        stream.write(bs);
	        stream.flush();
	        stream.close();*/
		}
		
		//RequestDispatcher view = request.getRequestDispatcher("result.jsp");  
		//view.forward(request, response);
	}
	
	private byte[] getClip( String requestUserId, String requestKey ) {
		byte[] data = null;
		EntityManager em = Emf.get().createEntityManager();
		//List< Splat > splatters = new ArrayList< Splat >();
		
		try {
	        // ... do stuff with em ...
			if ( null == em ) {
                System.out.println( "entityManagerFactory is hosed" );
			}
			Key parent = KeyFactory.createKey("users", Long.parseLong(requestUserId));
			Key child = KeyFactory.createKey(parent, "splats", Long.parseLong(requestKey));
			//has parent key users(1)/splats(3)
			
			Splat splatIt = em.find(Splat.class, child);
			data = splatIt.getSplat().getBytes();

			
			/*splatters = em.createQuery(
		    		//"select u.username from User u where u.username = :username")
		    		"select s from Splat s where s.splatId = :splatId")
		    		.setParameter("splatId", child)
		    		.getResultList();

	    if ( splatters.size() == 0 ) {
	    	System.out.println("!!!NO Splat EXIST!!!");
	    }
	    else {
	    	System.out.println(splatters);
	    	
	    	if ( splatters.size() == 1 ) {
	    		System.out.println("!!!Splat EXIST!!!");
	    	}
	    }*/
		} catch ( Exception e ) {
			System.out.println("PlayClip kaboom!");
    	} finally {
	        em.close();
	    }
		
		return data;
	}
	
	private byte[] decode( byte[] result ) {
		byte [] decoded = Base64.decodeBase64( result );
		
		return decoded;
	}
	
}
